# app/routes/mqtt.py
from flask import Blueprint, request
from flask_mqtt import Mqtt

mqtt = Mqtt()
mqtt_blueprint = Blueprint('mqtt_api', __name__)


@mqtt.on_connect()
def handle_mqtt_connect(client, userdata, flags, rc):
    print("Connected with result code ")
    # 在连接成功时执行的逻辑
    mqtt.subscribe('/flask/test')  # 订阅主题


@mqtt.on_message()
def handle_mqtt_message(client, userdata, message):
    payload = message.payload  # 获取消息载荷
    payload_str = payload.decode('utf-8')  # 将字节流解码为字符串
    print("Received message '" + payload_str + "' on topic '"
          + message.topic + "' with QoS " + str(message.qos))
    # 在接收到消息时执行的逻辑


@mqtt_blueprint.route('/api/mqtt_publish', methods=['POST', 'GET'])
def mqtt_publish():
    # 在这里处理 MQTT 发布逻辑
    # topic = request.json.get('topic')
    # message = request.json.get('message')
    mqtt.publish('/flask/test', payload='你好我来自flask')
    return "Message published"


@mqtt_blueprint.route('/api/mqtt_subscribe', methods=['POST'])
def mqtt_subscribe():
    # 在这里处理 MQTT 订阅逻辑
    topic = request.json.get('topic')
    mqtt.subscribe(topic)
    return "Subscribed to topic: " + topic
